<template>
    <div class="container">
       <!-- <canvas ref="canvas"  @mousedown="startDrawing" @mousemove="draw" 
        @mouseup="stopDrawing"
       ></canvas> -->
       <div class="box">
        <vue-esign ref="esign" :width="500" :height="300" :isCrop="isCrop" :lineWidth="lineWidth" :lineColor="lineColor"
      :bgColor.sync="bgColor" />
       </div>
       <div>
          <button @click="handleReset">清空画布</button>
          <button @click="saveSignature">生成图片</button>
          <button @click="downImg">下载图片</button>
       </div>
       <div class="img" v-if="resultImg">
        <img :src="resultImg" alt="">
       </div>
       
    </div>
</template>

<script>
import vueEsign from 'vue-esign'
export default {
  name: 'App',
  components: {
    vueEsign
  },
  data(){
    return {
      context:'',//canvas 上下文
      isDrawing: false,//是否正在绘制
      DataUrl:'',//签名图片的base64编码
      lineWidth: 6,
      lineColor: "#000000",
      bgColor: "",
      resultImg: "",
      isCrop: false,
    }
  },
  mounted(){

  },
  methods:{

    //清除画布
    handleReset(){
      this.$refs.esign.reset()
      this.resultImg = ''
    },
    //保存签名
    saveSignature(){
      // this.DataUrl =  this.$refs.canvas.toDataURL('image/png',1.0) //获取签名图片的base64编码
      this.$refs.esign.generate({
        format:'png',quality:0.8
      }).then((res)=>{
        console.log('res',res)
        this.resultImg = res;
      })
      .catch((err)=>{
         console.error('err',err)
         alert('生成图片失败',err.message)
      })
    },
    //封装下载图片方法
    downloadImg(url){
      const a = document.createElement('a');
      a.href = url
      a.download = '签名.png'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    },
    //下载图片
    downImg(){
      // console.log('this.isCanvasEmpty(canvas)',this.isCanvasBlank(canvas))
      // if(this.isCanvasBlank(canvas)){
      //   alert('请先绘制签名！')
      //   return  
      // }
      console.log('dataurl',this.resultImg)
      if(!this.resultImg){
        alert('请先生成图片！')
        return
      }
      this.downloadImg(this.resultImg)
    },
    //验证canvas画布是否为空
    isCanvasBlank(canvas) {
        var blank = document.createElement('canvas');//系统获取一个空canvas对象
        blank.width = canvas.width;
        blank.height = canvas.height;
        return canvas.toDataURL() == blank.toDataURL();//比较值相等则为空
    }
    
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.container{
  display: flex;
  justify-content: center;
  align-items:center;
  flex-direction: column;
}
.box{
  border:1px solid red;
  background:bisque;
  width:500px;
  height:300px
}
.img{
  border:1px solid red;
}
</style>
